package com.jims.master.modules.sys.security;

import com.jims.master.common.utils.*;
import com.jims.master.modules.base.user.entity.MasterBaseinfo;
import com.jims.master.modules.base.user.service.MasterBaseinfoService;
import com.jims.master.modules.sys.entity.SysLogger;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.service.SystemService;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * shiro密码验证类
 * 重写doCredentialsMatch方法，返回true验证通过
 * 返回false 验证不通过
 * Created by WangYQ on 2017/5/31.
 */
@Service
public class JimsCredentialsMatcher extends SimpleCredentialsMatcher {

    @Autowired
    private SystemService systemService;
    @Autowired
    private MasterBaseinfoService masterBaseinfoService;
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        String password = String.valueOf(usernamePasswordToken.getPassword());
        String mobileCode = usernamePasswordToken.getMobileCode();
        String type=usernamePasswordToken.getType();
        User user = getSystemService().getUserByLoginName(username);
//      不同人员在不同端口登录
        boolean flag=validatePwd(user,username,mobileCode,type,password);
        if(flag){
            try {
                saveSysLogger(user,((ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes())
                        .getRequest());

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 获取系统业务对象
     */
    public SystemService getSystemService() {
        if (systemService == null) {
            systemService = SpringContextHolder.getBean(SystemService.class);
        }
        return systemService;
    }
    /**
     * 判断是否验证成功
     * @param user
     * @param username
     * @param mobileCode
     * @param type
     * @param password
     * @return
     */
    public boolean validatePwd(User user,String username,String mobileCode,String type,String password){

        if(user!=null){
            if("3".equals(type)){
                String validateNum=(String)CacheUtils.get("validateNum_"+username);
                String phoneNum=(String)CacheUtils.get("phoneNum_"+username);
                if(StringUtils.isBlank(validateNum) || StringUtils.isBlank(phoneNum)){
                    return false;
                }
                if(phoneNum.equals(username)){
                    if(validateNum.equals(mobileCode)){
                        return true;
                    }else{
                        return  false;
                    }
                }else{
                    return  false;
                }
            }else{
                if(password.length()>24){
                    return equals(password,user.getPassword());
                }else{
                    return Entrypt.validatePassword(password,user.getPassword());
                }

            }
        }
        return false;
    }
    /**
     * 登录日志保存
     * @param user
     * @return
     */
    public void saveSysLogger(User user  ,HttpServletRequest request)throws IOException {
        String ip = "";
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        }else{
            ip =  request.getHeader("x-forwarded-for");
        }
        AddressUtils addressUtils=new AddressUtils();
        String address= addressUtils.getAddresses("ip="+ip, "utf-8");
        SysLogger sysLogger=new SysLogger();
        if (user.getMasterBaseinfo()!=null) {
            sysLogger.setLoginname(user.getMasterBaseinfo().getName());
        }
        sysLogger.setUser(user);
        sysLogger.setAdress(address);
        sysLogger.setLogintime(new Date());
        sysLogger.setIp(ip);
        getSystemService().createSysLogger(sysLogger);
    }
}
